package com.jiayi.cms.service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.doudou.core.container.ListUtil;
import com.doudou.core.lang.ObjUtil;
import com.doudou.core.number.NumUtil;
import com.doudou.core.str.StrUtil;
import com.jiayi.common.utils.PageUtils;
import com.jiayi.common.utils.poi.ExcelUtil;
import com.jiayi.data.entity.CmsAboutUsClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jiayi.common.core.page.TableDataInfo;
import com.jiayi.cms.mapper.JiayiAboutUsMapper;
import com.jiayi.data.entity.schema.JiayiAboutUs;
import com.jiayi.data.entity.excel.JiayiAboutUsExcel;
import com.jiayi.data.entity.bo.JiayiAboutUsBO;
import com.jiayi.data.entity.request.JiayiAboutUsRequest;
import com.jiayi.data.entity.request.JiayiAboutUsSearchRequest;
import com.jiayi.data.entity.request.JiayiAboutUsSearchPageRequest;
import com.jiayi.data.entity.response.JiayiAboutUsDTO;
import com.jiayi.data.converter.JiayiAboutUsConverter;
import com.jiayi.api.JiayiAboutUsService;
import com.jiayi.common.developutil.ConvertUtils;
import com.github.pagehelper.PageInfo;
import com.jiayi.common.utils.DateUtils;
import javax.servlet.http.HttpServletResponse;
import com.jiayi.common.constant.HttpStatus;
import static com.jiayi.common.utils.SecurityUtils.getUserIdStr;

/**
 * 关于我们配置Service业务层处理
 *
 * @author zzx
 * @date 2024-11-26
 */
@Service
@Slf4j
public class JiayiAboutUsServiceImpl implements JiayiAboutUsService {
    @Autowired
    private JiayiAboutUsMapper jiayiAboutUsMapper;

    @Autowired
    private JiayiAboutUsConverter jiayiAboutUsconverter;

    /**
     * 查询关于我们配置
     *
     * @param id 关于我们配置主键
     * @return 关于我们配置
     */
    @Override
    public JiayiAboutUsDTO selectJiayiAboutUsById(Long id) {
        JiayiAboutUs jiayiAboutUs = jiayiAboutUsMapper.selectJiayiAboutUsById(id);
        return jiayiAboutUsconverter.convertToJiayiAboutUsDTO(jiayiAboutUs);
    }

    /**
     * 查询关于我们配置列表
     *
     * @param request 关于我们配置
     * @return 关于我们配置
     */
    @Override
    public TableDataInfo selectJiayiAboutUsList(JiayiAboutUsSearchPageRequest request) {
        PageUtils.startPage(request.getPageNum(),request.getPageSize());
        JiayiAboutUs jiayiAboutUs = jiayiAboutUsconverter.convertToJiayiAboutUs(request);
        List<JiayiAboutUs> list = jiayiAboutUsMapper.selectJiayiAboutUsList(jiayiAboutUs);
        List<JiayiAboutUsDTO> dtos = ConvertUtils.convert(list, jiayiAboutUsconverter::convertToJiayiAboutUsDTO);
        return TableDataInfo.builder().code(HttpStatus.SUCCESS).msg("查询成功").rows(dtos).total(new PageInfo(list).getTotal()).build();
    }

    /**
     * 查询关于我们配置列表 不分页
     *
     * @param request 关于我们配置
     * @return 关于我们配置集合
     */
    public List<JiayiAboutUs> selectJiayiAboutUsList(JiayiAboutUsSearchRequest request){
        JiayiAboutUs jiayiAboutUs = jiayiAboutUsconverter.convertToJiayiAboutUs(request);
        List<JiayiAboutUs> list = jiayiAboutUsMapper.selectJiayiAboutUsList(jiayiAboutUs);
        return list;
    }

    /**
     * excel 导出 全量
     *
     * @param request 关于我们配置
     */
    public void export(JiayiAboutUsSearchRequest request, HttpServletResponse response){
        JiayiAboutUs jiayiAboutUs = jiayiAboutUsconverter.convertToJiayiAboutUs(request);
        List<JiayiAboutUs> list = jiayiAboutUsMapper.selectJiayiAboutUsList(jiayiAboutUs);
        List<JiayiAboutUsExcel> excelList = ConvertUtils.convert(list, jiayiAboutUsconverter::convertToJiayiAboutUsExcel);
        ExcelUtil<JiayiAboutUsExcel> util = new ExcelUtil<JiayiAboutUsExcel>(JiayiAboutUsExcel.class);
        util.exportExcel(response, excelList, "关于我们配置数据");
    }

    /**
     * 新增关于我们配置
     *
     * @param request 关于我们配置
     * @return 结果
     */
    @Override
    public int insertJiayiAboutUs(JiayiAboutUsRequest request) {
        JiayiAboutUs jiayiAboutUs = jiayiAboutUsconverter.convertToJiayiAboutUs(request);
        jiayiAboutUs.setCreateBy(getUserIdStr());
        jiayiAboutUs.setCreateTime(DateUtils.getNowDate());
        return jiayiAboutUsMapper.insertJiayiAboutUs(jiayiAboutUs);
    }

    /**
     * 修改关于我们配置
     *
     * @param request 关于我们配置
     * @return 结果
     */
    @Override
    public int updateJiayiAboutUs(JiayiAboutUsRequest request) {
        JiayiAboutUs jiayiAboutUs = jiayiAboutUsconverter.convertToJiayiAboutUs(request);
        jiayiAboutUs.setValue(parseAboutUsValue(request));
        return jiayiAboutUsMapper.updateJiayiAboutUs(jiayiAboutUs);
    }

    /**
     * 批量删除关于我们配置
     *
     * @param ids 需要删除的关于我们配置主键
     * @return 结果
     */
    @Override
    public int deleteJiayiAboutUsByIds(Long[] ids) {
        return jiayiAboutUsMapper.deleteJiayiAboutUsByIds(ids);
    }

    /**
     * 删除关于我们配置信息
     *
     * @param id 关于我们配置主键
     * @return 结果
     */
    @Override
    public int deleteJiayiAboutUsById(Long id) {
        return jiayiAboutUsMapper.deleteJiayiAboutUsById(id);
    }

    @Override
    public JiayiAboutUsDTO getInfoByKey(String key,Object data) {
        JiayiAboutUs jiayiAboutUs = jiayiAboutUsMapper.selectJiayiAboutUsByKey(key);
        JiayiAboutUsDTO jiayiAboutUsDTO = jiayiAboutUsconverter.convertToJiayiAboutUsDTO(jiayiAboutUs);
        parseAboutUsValue(jiayiAboutUsDTO,data);
        return jiayiAboutUsDTO;
    }

    /**
     * 格式化响应
     */
    private  void parseAboutUsValue(JiayiAboutUsDTO jiayiAboutUsDTO,Object data){
        if (ObjUtil.isNotNull(jiayiAboutUsDTO)){
            String value = jiayiAboutUsDTO.getValue();
            if (StrUtil.isNotBlank(value)) {
                String key = jiayiAboutUsDTO.getKey();
                Object valueObj;
                if (StrUtil.equals(key, "dev_history")) {
                    valueObj = JSONUtil.toList(value, CmsAboutUsClass.DevHistory.class);
                } else if (StrUtil.equals(key, "company_honor")) {
                    CmsAboutUsClass.CompanyHonor query = JSONUtil.parseObj(data).toBean(CmsAboutUsClass.CompanyHonor.class);
                    List<CmsAboutUsClass.CompanyHonor> list = JSONUtil.toList(value, CmsAboutUsClass.CompanyHonor.class);
                    valueObj = list.stream().filter(o ->{//查询
                        boolean nameFlag = true, typeFlag = true;
                        if (StrUtil.isNotBlank(query.getName())){ nameFlag = StrUtil.contains(o.getName(), query.getName()); }
                        if (StrUtil.isNotBlank(query.getType())){ typeFlag = StrUtil.equals(o.getType(), query.getType()); }
                        return nameFlag && typeFlag;
                    }).collect(Collectors.toList());
                } else if (StrUtil.equals(key, "call_us")) {
                    valueObj = JSONUtil.parseObj(value).toBean(CmsAboutUsClass.CallUs.class);
                } else if (StrUtil.equals(key, "home_image")){
                    valueObj = JSONUtil.parseArray(value);
                } else {
                    valueObj = value;
                }
                jiayiAboutUsDTO.setValueObj(valueObj);
            }
        }
    }

    /**
     * 格式化请求
     */
    private  String parseAboutUsValue(JiayiAboutUsRequest jiayiAboutUsRequest){
        if (ObjUtil.isNotNull(jiayiAboutUsRequest)){
            Object valueObj = jiayiAboutUsRequest.getValueObj();
            if (ObjUtil.isNotNull(valueObj)) {
                String key = jiayiAboutUsRequest.getKey();
                String value = StrUtil.toString(valueObj);
                //注：修改的时候valueObj作为单个对象使用
                if (StrUtil.equals(key, "dev_history")) {/* 发展历程 */
                    JiayiAboutUs jiayiAboutUs = jiayiAboutUsMapper.selectJiayiAboutUsByKey(key);
                    List<CmsAboutUsClass.DevHistory> devHistoryList = JSONUtil.toList(jiayiAboutUs.getValue(), CmsAboutUsClass.DevHistory.class);
                    if (JSONUtil.isTypeJSON(value)){
                        CmsAboutUsClass.DevHistory devHistory = JSONUtil.parseObj(valueObj).toBean(CmsAboutUsClass.DevHistory.class);
                        if (ObjUtil.isNotNull(devHistory.getId())){
                            devHistoryList.set(devHistory.getId()-1,devHistory);
                        }else {
                            devHistoryList.add(devHistory);
                        }
                    }else {//删除
                        devHistoryList.remove(NumUtil.parseInt(value)-1);
                    }
                    //排序
                    devHistoryList = ListUtil.sort(devHistoryList, ((o1, o2) -> o2.getDate().compareTo(o1.getDate())));
                    for (int i = 0; i < devHistoryList.size(); i++) {//重新赋id
                        devHistoryList.get(i).setId(i+1);
                    }
                    value = JSONUtil.toJsonStr(devHistoryList);
                } else if (StrUtil.equals(key, "company_honor")) {/* 资质荣誉 */
                    JiayiAboutUs jiayiAboutUs = jiayiAboutUsMapper.selectJiayiAboutUsByKey(key);
                    List<CmsAboutUsClass.CompanyHonor> companyHonorList = JSONUtil.toList(jiayiAboutUs.getValue(), CmsAboutUsClass.CompanyHonor.class);
                    if (JSONUtil.isTypeJSON(value)){
                        CmsAboutUsClass.CompanyHonor companyHonor = JSONUtil.parseObj(valueObj).toBean(CmsAboutUsClass.CompanyHonor.class);
                        if (ObjUtil.isNotNull(companyHonor.getId())){
                            companyHonorList.set(companyHonor.getId()-1, companyHonor);
                        }else {
                            companyHonorList.add(companyHonor);
                        }
                    }else {//删除
                        companyHonorList.remove(NumUtil.parseInt(value)-1);
                    }
                    //排序
                    companyHonorList = ListUtil.sort(companyHonorList, ((o1, o2) -> o2.getDate().compareTo(o1.getDate())));
                    for (int i = 0; i < companyHonorList.size(); i++) {//重新赋id
                        companyHonorList.get(i).setId(i+1);
                    }
                    value = JSONUtil.toJsonStr(companyHonorList);
                } else if (StrUtil.equals(key, "call_us")) {/* 联系我们 */
                    JiayiAboutUs jiayiAboutUs = jiayiAboutUsMapper.selectJiayiAboutUsByKey(key);
                    CmsAboutUsClass.CallUs callUs = JSONUtil.parseObj(jiayiAboutUs.getValue()).toBean(CmsAboutUsClass.CallUs.class);
                    JSONObject valueJsonObj = JSONUtil.parseObj(valueObj);
                    String order = valueJsonObj.getStr("order");
                    String data = valueJsonObj.getStr("data");
                    boolean isDel = NumUtil.isNumber(data);
                    if (StrUtil.equals(order, "address")){
                        if (isDel){
                            callUs.getCallUsAddressList().remove(NumUtil.parseInt(data)-1);
                        }else {
                            CmsAboutUsClass.CallUsAddress bean = valueJsonObj.getBean("data",CmsAboutUsClass.CallUsAddress.class);
                            if (ObjUtil.isNotNull(bean.getId())){
                                callUs.getCallUsAddressList().set(bean.getId()-1, bean);
                            }else {
                                callUs.getCallUsAddressList().add(bean);
                            }
                        }
                        callUs.parseAddressList();
                    }else if (StrUtil.equals(order, "manager")){
                        if (isDel){
                            callUs.getCallUsManagerList().remove(NumUtil.parseInt(data)-1);
                        }else {
                            CmsAboutUsClass.CallUsManager bean = valueJsonObj.getBean("data",CmsAboutUsClass.CallUsManager.class);
                            if (ObjUtil.isNotNull(bean.getId())){
                                callUs.getCallUsManagerList().set(bean.getId()-1, bean);
                            }else {
                                callUs.getCallUsManagerList().add(bean);
                            }
                        }
                        callUs.parseManagerList();
                    }else {
                        if (isDel){
                            callUs.getCallUsEmailList().remove(NumUtil.parseInt(data)-1);
                        }else {
                            CmsAboutUsClass.CallUsEmail bean = valueJsonObj.getBean("data",CmsAboutUsClass.CallUsEmail.class);
                            if (ObjUtil.isNotNull(bean.getId())){
                                callUs.getCallUsEmailList().set(bean.getId()-1, bean);
                            }else {
                                callUs.getCallUsEmailList().add(bean);
                            }
                        }
                        callUs.parseEmailList();
                    }
                    value = JSONUtil.toJsonStr(callUs);
                }else if (StrUtil.equals(key, "home_image")){
                    JiayiAboutUs jiayiAboutUs = jiayiAboutUsMapper.selectJiayiAboutUsByKey(key);
                    List<CmsAboutUsClass.HomeImage> homeImageList = JSONUtil.toList(jiayiAboutUs.getValue(), CmsAboutUsClass.HomeImage.class);
                    if (JSONUtil.isTypeJSON(value)){
                        CmsAboutUsClass.HomeImage homeImage = JSONUtil.parseObj(valueObj).toBean(CmsAboutUsClass.HomeImage.class);
                        homeImageList.add(homeImage);
                    }else {//删除
                        homeImageList.remove(NumUtil.parseInt(value)-1);
                    }
                    //排序
                    for (int i = 0; i < homeImageList.size(); i++) {//重新赋id
                        homeImageList.get(i).setId(i+1);
                    }
                    value = JSONUtil.toJsonStr(homeImageList);
                }
                return value;
            }
        }
        return null;
    }
}
